package com.ok.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.ok.common.utils.AdminContext;
import com.ok.common.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName AdminInfoInterceptor
 * @Description TODO
 * @Author hw
 * @Date 2024/5/7 14:27
 */
@Slf4j
public class AdminInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的用户信息
        String adminInfo = request.getHeader("admin-info");
        log.info("请求头中的管理员信息：{}", adminInfo);
        // 2.判断是否为空
        if (StrUtil.isNotBlank(adminInfo)) {
            // 不为空，保存到ThreadLocal
            AdminContext.setAdmin(Long.valueOf(adminInfo));
        }
        // 3.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        AdminContext.removeAdmin();
    }
}
